<template>
    <textarea ref="editor"></textarea>
</template>

<script>
export default {
    name: 'md-editor',
    props: ['value'],
    data() {
        return {
            syncValue: '',
        }
    },
    mounted() {
        this.editor = new SimpleMDE({
            element: this.$refs.editor,
            spellChecker: false,
            tabSize: 4,
            initialValue: _.defaultTo(this.value, ''),
        })

        this.editor.codemirror.on('change', _.debounce(() => {
            console.log('[md-editor] change')
            const value = this.editor.value()
            this.syncValue = value
            this.$emit('input', value)
        }, 600))
    },
    watch: {
        value(val) {
            if (val === this.syncValue) {
                return
            }
            console.log('[md-editor] watch')
            this.editor.value(_.defaultTo(val, ''))
        },
    }
}
</script>
